package com.by.cloud.common;

import com.by.cloud.annotation.PreAuthorize;
import com.by.cloud.enums.UserRoleEnum;
import com.by.cloud.exception.BusinessException;
import com.by.cloud.exception.ErrorCode;
import com.by.cloud.model.vo.user.UserVo;
import com.by.cloud.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 权限校验切面
 *
 * @author lzh
 */
@Component
@Aspect
public class AuthAspect {

    @Resource
    private UserService userService;

    /**
     * 权限校验
     *
     * @param joinPoint    连接点
     * @param preAuthorize 注解
     * @return 返回值
     * @throws Throwable 异常
     */
    @Around("@annotation(preAuthorize)")
    public Object authCheck(ProceedingJoinPoint joinPoint, PreAuthorize preAuthorize) throws Throwable {
        // 获取当前登录用户
        UserVo userInfo = userService.getCurrentUserInfo();
        // 获取登录的用户角色
        Integer userRole = userInfo.getUserRole();
        UserRoleEnum roleEnum = UserRoleEnum.getEnumByValue(userRole);
        // 获取指定的用户角色
        UserRoleEnum mustRole = preAuthorize.role();
        if (!mustRole.equals(roleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 放行
        return joinPoint.proceed();
    }
}
